import React from 'react'
import Docxtemplater from 'docxtemplater'
import PizZip from 'pizzip'
import { saveAs } from 'file-saver'
import ImageModule from 'docxtemplater-image-module-free'

const ExportWordComponent = ({ reportData }) => {
  const handleExport = async () => {
    try {
      // 1. 加载模板文件
      const response = await fetch('/report_template.docx')
      const buffer = await response.arrayBuffer()

      // 2. 图片处理配置
      const imageOptions = {
        getImage: (tagValue) => {
          return fetch(tagValue)
            .then((res) => res.blob())
            .then(
              (blob) =>
                new Promise((resolve) => {
                  const reader = new FileReader()
                  reader.onload = () => resolve(reader.result.split(',')[1])
                  reader.readAsDataURL(blob)
                })
            )
        },
        getSize: () => [300, 200], // 固定图片尺寸
      }

      // 3. 生成文档
      const zip = new PizZip(buffer)
      const doc = new Docxtemplater()
        .loadZip(zip)
        .attachModule(new ImageModule(imageOptions))

      doc.render({
        ...reportData,
        date: new Date().toLocaleDateString(),
        logo: reportData.logoUrl, // 支持Base64或URL
      })

      saveAs(doc.getZip().generate({ type: 'blob' }), 'report.docx')
    } catch (error) {
      console.error('导出失败:', error)
    }
  }

  return (
    <button onClick={handleExport} className="export-button">
      导出Word报告
    </button>
  )
}

export default ExportWordComponent
